package cn.darkhorse.mesadmin.controller.device;

import cn.darkhorse.alarm.pojo.AlarmRecordInfo;
import cn.darkhorse.alarm.pojo.AlarmParameterSettings;
import cn.darkhorse.alarm.service.AlarmParameterSettingsService;
import cn.darkhorse.alarm.service.AlarmRecordInfoService;
import cn.darkhorse.device.dto.MesDeviceDTO;
import cn.darkhorse.device.dto.queryparam.AcquisitionDeviceQueryParamDTO;
import cn.darkhorse.device.pojo.*;
import cn.darkhorse.device.service.*;
import cn.darkhorse.device.vo.ExtraInfoVO;
import cn.darkhorse.device.vo.MesDeviceVO;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.darkhorse.common.constant.CommonConstant.MES_DEVICE_ACQUISITION_YES;

/**
 * <p>
 * 设备闲置表 前端控制器
 * </p>
 * @author yuanjun
 * @since 2022/11/10 16:24
 */
@Api(tags = "设备管理")
@RestController
@RequestMapping("/device/mesDevice")
public class MesDeviceController extends BaseController {


    @Resource
    private MesDeviceService mesDeviceService;

    @Resource
    private AlarmParameterSettingsService alarmParameterSettingsService;

    @Resource
    private AlarmRecordInfoService alarmRecordInfoService;

    @Resource
    private HardwareService hardwareService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IotGatewayService iotGatewayService;
    @Resource
    private IotPointTableService iotPointTableService;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MesReportSettingService reportSettingService;

    @Autowired
    private MesDeviceTypeService mesDeviceTypeService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysDictDataService dictDataService;

    private MybatisAutoConfiguration.MapperScannerRegistrarNotFoundConfiguration mapperScannerRegistrarNotFoundConfiguration;

    /**
     * 设备列表
     * @return
     */
    @ApiOperation(value = "设备列表")
    @RequestMapping("/list")
    public TableDataInfo listMesDevice(MesDevice device) {
        startPage();
        LambdaQueryWrapper<MesDevice> queryWrapper = new LambdaQueryWrapper<>();
        // 所属部门作为查询条件
        if (device.getDept() != null) {
            queryWrapper.eq(MesDevice::getDept, device.getDept());
        }

        // 设备名称作为查询条件
        if (StringUtils.isNotBlank(device.getName())) {
            queryWrapper.like(MesDevice::getName, device.getName());
        }
        // 设备编号作为查询条件
        if (null != device.getCode()) {
            queryWrapper.like(MesDevice::getCode, device.getCode());
        }

//        if (null != device.getDeviceStatus()) {
//            queryWrapper.eq(MesDevice::getDeviceStatus, device.getDeviceStatus());
//        }
        if (null != device.getType()) {
            queryWrapper.eq(MesDevice::getType, device.getType());
        }
        if (null != device.getModel()) {
            queryWrapper.like(MesDevice::getModel, device.getModel());
        }

        queryWrapper.orderByDesc(MesDevice::getGmtCreate);

        List<MesDevice> devices = mesDeviceService.list(queryWrapper);
        for (MesDevice mesDevice : devices) {
            SysDept sysDept = sysDeptService.selectDeptById(mesDevice.getDept());
            if (sysDept != null){
                mesDevice.setDeptName(sysDept.getDeptName());
            }
            MesDeviceType deviceType = mesDeviceTypeService.getById(mesDevice.getType());
            if (deviceType != null){
                mesDevice.setTypeName(deviceType.getTypeName());
            }
            if (mesDevice.getCarBrand()!=null){
                mesDevice.setCarBrand(dictDataService.selectDictLabel("car_brand", mesDevice.getCarBrand()));
            }
        }
        return getDataTable(devices);
    }

    /**
     * 设备列表
     * @return
     */
    @ApiOperation(value = "选择设备列表")
    @RequestMapping("/myDeviceList")
    public AjaxResult myDeviceList() {
        LambdaQueryWrapper<MesDevice> queryWrapper = new LambdaQueryWrapper<>();
//        Long userId = getUserId();
//        queryWrapper.eq(MesDevice::getOperatorId, userId);
//        queryWrapper.eq(MesDevice::getDeviceStatus, 1);
        return AjaxResult.success(mesDeviceService.list(queryWrapper));
    }
    /**
     * 获取硬件设备列表，只返回deviceId
     * @return
     */
    @RequestMapping("/hardware/list")
    public TableDataInfo getHardwareList(String deviceId) {
        // Step.1获取所有数据采集设备
        List<MesDevice> deviceList = mesDeviceService.list();

        Set<String> deviceIdSet = new HashSet<>();
        deviceList.forEach(item-> {
            if (StringUtils.isBlank(item.getGatewayDeviceId())) {
                return;
            }

            deviceIdSet.add(item.getGatewayDeviceId());
        });

        startPage();
        List<MesDeviceNameMapping> list = hardwareService.getList(deviceId);

        list.forEach(item-> {
            boolean contains = deviceIdSet.contains(item.getDataDeviceId());
            item.setBeUsed(contains);
        });

        return getDataTable(list);
    }

//    /**
//     * 根据部门 查询所有采集设备
//     * @param dto
//     * @return
//     */
//    @RequestMapping("/acquisition/list")
//    public TableDataInfo acquisitionDeviceList(AcquisitionDeviceQueryParamDTO dto) {
//        startPage();
//        /*if(null==dto.getIsAcquisitionDevice()) {
//            dto.setIsAcquisitionDevice(MES_DEVICE_ACQUISITION_YES);
//        }*/
//        LambdaQueryWrapper<MesDevice> queryWrapper=getWrapper(dto);
//        List<MesDevice> list = mesDeviceService.list(queryWrapper);
//        return getDataTable(list);
//    }

    /**
     * 根据部门 查询所有采集设备,未设置data_device_id字段的
     * @param dto
     * @return
     */
    @RequestMapping("/acquisition/list2")
    public TableDataInfo acquisitionDeviceList2(AcquisitionDeviceQueryParamDTO dto) {
        startPage();
        if(null==dto.getIsAcquisitionDevice()) {
            dto.setIsAcquisitionDevice(MES_DEVICE_ACQUISITION_YES);
        }
        LambdaQueryWrapper<MesDevice> queryWrapper= new LambdaQueryWrapper<>();
//        queryWrapper.isNull(MesDevice::getGatewayDeviceId);
        queryWrapper.and(qw-> qw.isNull(MesDevice::getGatewayDeviceId).or().eq(MesDevice::getGatewayDeviceId, ""));

        List<MesDevice> list = mesDeviceService.list(queryWrapper);

        return getDataTable(list);
    }


    /**
     * 添加或者修改设备信息
     * @param mesDevice
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "添加或者修改设备信息")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(@Validated @RequestBody MesDevice mesDevice, HttpServletRequest request) {

//        // 因为前端传来的是null,需要处理一下改成空字符串
//        device.setWorkTeam(StringUtils.isBlank(device.getWorkTeam())?"":device.getWorkTeam());
        doValidate(mesDevice);



        boolean b = mesDeviceService.saveOrUpdate(mesDevice);
        return AjaxResult.success(b);
    }
    /**
     * 校验是否符合校验规则
     * @param device
     */
    private void doValidate(MesDevice device) {
        if (device.getId() == null) {
            // 没有id，说明是新增操作，需要校验设备编号是否已经存在
            long count = mesDeviceService.count(new LambdaQueryWrapper<MesDevice>()
                    .eq(MesDevice::getCode, device.getCode()));
            if (count > 0) {
                throw new ServiceException("已存在该设备编号");
            }

        } else {
            long count = mesDeviceService.count(new LambdaQueryWrapper<MesDevice>()
                    .eq(MesDevice::getCode, device.getCode())
                    .ne(MesDevice::getId,device.getId()));
            if (count > 0) {
                throw new ServiceException("已存在该设备编号");
            }
        }
    }

    /**
     * 删除设备
     * 注意：存在后续业务时不可删除
     * @param id 设备id
     * @return
     */
    @ApiOperation(value = "删除设备")
    @RequestMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult del(Long id) {
//        List<String> list = doValidate(deviceId);
//        if (!list.isEmpty()) {
//            throw new ServiceException(String.format("该设备存在以下业务：%s，不允许删除",StringUtils.join(list,"、")));
//        }
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotGateway::getDeviceId,id);
        wrapper.eq(IotGateway::getDeviceType,0);
        long count = iotGatewayService.count(wrapper);
        if(count>0){
            throw new ServiceException("该设备处于实时监控中，无法删除!");
        }
        boolean result = mesDeviceService.removeById(id);
        return AjaxResult.success(result);
    }



    /**
     * 查看设备信息
     * @param id 设备id
     * @return
     */
    @ApiOperation(value = "查看设备信息")
    @RequestMapping("/view")
    public AjaxResult view(Long id) {
        MesDevice mesDevice = mesDeviceService.getById(id);
        if (mesDevice == null) {
            throw new ServiceException("未查询到设备信息");
        }
        SysDept sysDept = sysDeptService.selectDeptById(mesDevice.getDept());
        if (sysDept != null){
            mesDevice.setDeptName(sysDept.getDeptName());
        }
        MesDeviceType deviceType = mesDeviceTypeService.getById(mesDevice.getType());
        if (deviceType != null){
            mesDevice.setTypeName(deviceType.getTypeName());
        }
        return AjaxResult.success(mesDevice);
    }
    /**
     * 查看设备信息
     * @param deviceCode 设备编码
     * @return
     */
    @RequestMapping("/view-qrcode")
    public AjaxResult viewByQRCode(String  deviceCode) {
        LambdaQueryWrapper<MesDevice> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesDevice::getCode,deviceCode);
        MesDevice mesDevice = mesDeviceService.getOne(wrapper);
        if (mesDevice == null) {
            throw new ServiceException("请扫描正确的二维码");
        }
        MesDeviceVO vo = new MesDeviceVO();
        BeanUtils.copyProperties(mesDevice,vo);

        long count = 0L;
        vo.setFieldIsAcquisitionDeviceCanBeModified(count > 0 ? false : true);

        long count2 = 0L;
        vo.setFieldIsCapacityDeviceCanBeModified(count2 > 0 ? false : true);

        vo.setFieldIsCapacityDeviceCanBeModified(count2 > 0 ? false : true);
        return AjaxResult.success(vo);
    }

    /**
     * 是否存在后续业务
     * @param deviceId 设备id
     * @return
     */
    @RequestMapping("/subsequentBusiness/exists")
    public AjaxResult subsequentBusinessExists(Long deviceId) {
        JSONObject jsonObject = new JSONObject();
        List<String> list = doValidate(deviceId);

        jsonObject.put("exists",StringUtils.join(list,","));
        return AjaxResult.success(jsonObject);
    }

    /**
     * 判断是否有后续业务，存在后续业务抛出异常，后续业务包括：盘点、异动、闲置、维修、点检、保养、开机信息
     * @param deviceId
     * @return
     */
    private List<String> doValidate(Long deviceId) {
        List<String> list = new ArrayList<>();

//        //维修
//        LambdaQueryWrapper<MesRepairInfo> repairWrapper=new LambdaQueryWrapper<>();
//        repairWrapper.eq(MesRepairInfo::getDeviceId,deviceId);
//        long repairCount=mesRepairInfoService.count(repairWrapper);
//        if(repairCount>0){
//            list.add("维修");
//        }
//        //点检
//        LambdaQueryWrapper<MesCheckPlanDevice> checkWrapper=new LambdaQueryWrapper<>();
//        checkWrapper.eq(MesCheckPlanDevice::getDeviceId,deviceId);
//        long checkCount=mesCheckPlanDeviceService.count(checkWrapper);
//        if(checkCount>0){
//            list.add("点检");
//        }
//        //保养
//        LambdaQueryWrapper<MesMaintenancePlanDevice> maintenanceWrapper=new LambdaQueryWrapper<>();
//        maintenanceWrapper.eq(MesMaintenancePlanDevice::getDeviceId,deviceId);
//        long maintenanceCount=mesMaintenancePlanDeviceService.count(maintenanceWrapper);
//        if(maintenanceCount>0){
//            list.add("保养");
//        }

        return list;

    }

    /**
     * 采集设备类型列表
     * @return
     */
    @RequestMapping("/acquisition/device/type/list")
    public AjaxResult acquisitionDeviceType() {
        return AjaxResult.success(mesDeviceService.acquisitionDeviceTypeList());
    }


//
//    /**
//     * 查看设备信息
//     * @param deviceId 设备id
//     * @return
//     */
//    @RequestMapping("/view-report")
//    public AjaxResult reportView(Long deviceId) {
//
//        MesDevice mesDevice = mesDeviceService.getById(deviceId);
//        if (mesDevice == null) {
//            return AjaxResult.success(new JSONObject());
//        }
//        if (mesDevice.getHistoryTableName() == null || mesDevice.getHistoryTableName().trim().isEmpty()){
//            return AjaxResult.success(new JSONObject());
//        }
//
//        if (!mesDevice.getDeviceOnline()){
//            return AjaxResult.success(new JSONObject());
//        }
////        List<MesDevice> deviceList = mesDeviceService.lambdaQuery().eq(MesDevice::getParentId, deviceId).list();
//        List<String> deviceIds = new ArrayList<>();
//        deviceIds.add(mesDevice.getGatewayDeviceId());
////        if (deviceList != null && !deviceList.isEmpty()){
////            for (MesDevice device : deviceList) {
////                deviceIds.add(device.getGatewayDeviceId());
////            }
////        }
//        String sql;
//
//        sql = "SELECT * from mqtt_live_data where device_id in {0}";
//
//        List<Map<String, Object>> mapList = SqlRunner.db().selectList(sql, deviceIds);
//
//
//        JSONObject param = new JSONObject();
//
//        if (mapList == null){
//            return AjaxResult.success(new JSONObject());
//        }
//        for (Map<String, Object> map : mapList) {
//            System.out.println(map);
//            JSONObject data = JSONObject.parseObject((String) map.get("data"));
//            JSONObject params = data.getJSONObject("params");
//            if (params != null){
//                param.putAll(params);
//            }
//        }
//
//        List<IotPointTable> pointTables = iotPointTableService.lambdaQuery()
//                .in(IotPointTable::getGatewayDeviceId, deviceIds)
//                .list();
//        pointTables.forEach(pointTable -> {
//            Object value = param.get(pointTable.getFieldName());
//            if (value != null){
//                if (!(value instanceof ExtraInfoVO)){
//                    Object result = iotPointTableService.buildValue(pointTable, value);
//                    ExtraInfoVO extraInfoVO = iotPointTableService.translateValue2(pointTable, String.valueOf(result));
//                    param.put(pointTable.getFieldName(), extraInfoVO);
//                }
//            }else {
//                ExtraInfoVO extraInfoVO = new ExtraInfoVO("--","");
//                param.put(pointTable.getFieldName(), extraInfoVO);
//            }
//        });
//        List<AlarmParameterSettings> settingsList = alarmParameterSettingsService.lambdaQuery()
//                .eq(AlarmParameterSettings::getDeviceId, deviceId)
//                .list();
//
//        Set<String> alarmParams = new HashSet<>();
//        LocalDateTime time = LocalDateTime.now().plusSeconds(-60);
//        Map<String, String> collected = pointTables.stream().collect(Collectors
//                .toMap(IotPointTable::getFieldName, IotPointTable::getPointName, (v1, v2) -> v2,HashMap::new));
//
//
//        if (!settingsList.isEmpty()){
//
//            List<AlarmRecordInfo> recordInfos = alarmRecordInfoService.lambdaQuery().eq(AlarmRecordInfo::getDeviceId, deviceId).ge(AlarmRecordInfo::getAlarmDate, time)
//                    .in(AlarmRecordInfo::getParameterId, settingsList.stream().map(AlarmParameterSettings::getId).collect(Collectors.toList())).list();
//            for (AlarmRecordInfo recordInfo : recordInfos) {
//                for (AlarmParameterSettings settings : settingsList){
//                    if (recordInfo.getParameterId().equals(settings.getId())){
//                        alarmParams.add(settings.getFieldName());
//                        System.out.println("filedName: "+settings.getFieldName());
//                    }
//                }
//            }
//        }
//        JSONObject reportData = buildReportData(param, collected, alarmParams);
//        JSONObject sxt = new JSONObject();
//        sxt.put("url1", mesDevice.getCameraUrl1());
//        sxt.put("url2", mesDevice.getCameraUrl2());
//        reportData.put("sxt", sxt);
//        return AjaxResult.success( reportData);
//    }
//
//    @RequestMapping("/running-report")
//    public AjaxResult runningList(Long deviceId) {
//        MesDevice device = mesDeviceService.getById(deviceId);
//        List<MesDevice> children = mesDeviceService.lambdaQuery().eq(MesDevice::getParentId, deviceId).list();
//        if (device == null) {
//            return AjaxResult.success(new JSONArray());
//        }
//        if (device.getHistoryTableName() == null || device.getHistoryTableName().trim().isEmpty()){
//            return AjaxResult.success(new JSONArray());
//        }
//        if (!device.getDeviceOnline()){
//            return AjaxResult.success(new JSONArray());
//        }
//        String sql;
//
//        sql = "SELECT * from mqtt_live_data where device_id in {0}";
//        List<String> ids = children.stream().map(MesDevice::getGatewayDeviceId).collect(Collectors.toList());
//        ids.add(device.getGatewayDeviceId());
//        List<Map<String, Object>> maps = SqlRunner.db().selectList(sql, ids);
//        HashMap<String, Object> hashMap = new HashMap<>();
//        JSONObject param = new JSONObject();
//        for (Map<String, Object> map : maps) {
//            JSONObject data = JSONObject.parseObject((String) map.get("data"));
//            JSONObject object = data.getJSONObject("params");
//            if (object == null){
//                continue;
//            }
//            param.putAll(data.getJSONObject("params"));
//            hashMap.put((String) map.get("device_id"),map.get("add_date"));
//        }
//
//
//        List<IotPointTable> pointTables = iotPointTableService.lambdaQuery()
//                .in(IotPointTable::getGatewayDeviceId, ids)
//                .list();
//        JSONArray res = new JSONArray();
//        for (IotPointTable pointTable : pointTables) {
//            JSONObject object = new JSONObject();
//            object.put("name",pointTable.getPointName());
//            object.put("date",hashMap.get(pointTable.getGatewayDeviceId()));
//            Object val = param.get(pointTable.getFieldName());
//            if (val == null){
//                continue;
//            }
//            val = iotPointTableService.buildValue(pointTable,val);
//            val = iotPointTableService.translateValue(pointTable, String.valueOf(val));
//            object.put("value",val);
//            res.add(object);
//            if (res.size()>=20){
//                break;
//            }
//        }
//        return AjaxResult.success(res);
//    }

    @RequestMapping("/alarm-report")
    public AjaxResult alarmList(Long deviceId) {
        MesDevice device = mesDeviceService.getById(deviceId);
        if (device == null) {
            return AjaxResult.success(new JSONArray());
        }
        if (device.getHistoryTableName() == null || device.getHistoryTableName().trim().isEmpty()){
            return AjaxResult.success(new JSONArray());
        }
        if (!device.getDeviceOnline()){
            return AjaxResult.success(new JSONArray());
        }
        Boolean hasKey = redisCache.hasKey("report_alarm_last:"+deviceId);
        if (!hasKey) {
            Long count = alarmRecordInfoService.lambdaQuery().eq(AlarmRecordInfo::getDeviceId, deviceId).count();
            if (count >= 20L) {
                count = count - 20L;
            }
            redisCache.setCacheObject("report_alarm_last:"+deviceId, count);
        }
//        Long lastId = redisCache.getCacheObject("report_alarm_last:"+deviceId);


//        List<AlarmRecordInfo> recordInfos = alarmRecordInfoService.lambdaQuery().eq(AlarmRecordInfo::getDeviceId, deviceId)
//                .gt(AlarmRecordInfo::getId, lastId).list();
        List<AlarmRecordInfo> recordInfos = alarmRecordInfoService.lambdaQuery()
                .eq(AlarmRecordInfo::getDeviceId, deviceId)
                .orderByDesc(AlarmRecordInfo::getAlarmDate).last("limit 20")
                .list();
        if (!recordInfos.isEmpty()){
            redisCache.setCacheObject("report_alarm_last:"+deviceId, recordInfos.get(recordInfos.size() - 1).getId());
        }
        JSONArray res = new JSONArray();
        for (AlarmRecordInfo recordInfo : recordInfos) {
            AlarmParameterSettings parameterSettings = alarmParameterSettingsService.getById(recordInfo.getParameterId());
            JSONObject object = new JSONObject();
            object.put("name",parameterSettings.getPointName());
//            object.put("value",recordInfo.getAlarmValue());
//            object.put("limitValue",recordInfo.getLimitValue());
            object.put("value",recordInfo.getAlarmMessage());
            object.put("date",recordInfo.getAlarmDate());
            res.add(object);
        }
        return AjaxResult.success(res);
    }



    private JSONObject buildReportData(JSONObject obj,Map<String,String> collected,Set<String> alarmParams){
        JSONObject res = new JSONObject();

        List<MesReportSetting> settings = reportSettingService.lambdaQuery()
                .eq(MesReportSetting::getReportCode, "device_v1").list();
        // 使用Stream API根据属性B分组
        Map<String, List<MesReportSetting>> groupedMap = settings.stream()
                .collect(Collectors.groupingBy(MesReportSetting::getModleName));

        Set<String> processedFields = new HashSet<>(); // 已处理的字段
        Set<String> models = groupedMap.keySet();
        models.forEach(key -> {
            JSONArray modelArr = new JSONArray();
            List<MesReportSetting> list = groupedMap.get(key);
            for (MesReportSetting setting: list) {

                JSONObject object = obj.getJSONObject(setting.getFieldName());
                System.out.println(object);

                if (object == null){
                    continue;
                }
                object.put("name", collected.get(setting.getFieldName()));


                if (alarmParams.contains(setting.getFieldName())){
                    object.put("alarm", true);
                }else {
                    object.put("alarm", false);
                }
                modelArr.add(object);
                processedFields.add(setting.getFieldName());
            }

            res.put(key, modelArr);
        });

        // 创建其他未被取用过的字段集合
        JSONArray other = new JSONArray();


        // 遍历所有字段，检查哪些字段未被处理过
        for (String key : obj.keySet()) {
            if (!processedFields.contains(key)) {
                System.out.println(key);
                System.out.println(obj);
                if (! (obj.get(key) instanceof JSONObject)){
                    continue;
                }
                JSONObject object = obj.getJSONObject(key);

                if (object==null){
                    continue;
                }
                object.put("name", collected.get(key));


                if (alarmParams.contains(key)){
                    object.put("alarm", true);
                }else {
                    object.put("alarm", false);
                }
                other.add(object);
            }
        }
        res.put("other", other);

        return res;
    }


}
